// pages/scenic/detail/detail.js
Page({
  data: {
    id: null,
    scenicArea: null,
    tickets: [],
    hotels: [],
    loading: false,
    error: false,
    errorMsg: ''
  },

  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.loadData();
    } else {
      this.setData({
        error: true,
        errorMsg: '参数错误'
      });
    }
  },
  
  // 加载景区详情数据
  loadData: function() {
    this.setData({ 
      loading: true,
      error: false 
    });
    
    // 加载景区详情
    wx.mRequest({
      url: '/api/scenic/' + this.data.id,
      method: 'GET',
      success: (res) => {
        this.setData({
          scenicArea: res.data,
          loading: false
        });
        
        // 加载景区门票
        this.loadTickets();
        
        // 加载附近酒店
        this.loadHotels();
      },
      fail: (err) => {
        this.setData({
          loading: false,
          error: true,
          errorMsg: '加载景区信息失败'
        });
      }
    });
  },
  
  // 加载门票信息
  loadTickets: function() {
    wx.mRequest({
      url: '/api/ticket/list',
      method: 'GET',
      data: {
        scenicAreaId: this.data.id
      },
      success: (res) => {
        this.setData({
          tickets: res.data || []
        });
      }
    });
  },
  
  // 加载酒店信息
  loadHotels: function() {
    wx.mRequest({
      url: '/api/hotel/list',
      method: 'GET',
      data: {
        scenicAreaId: this.data.id
      },
      success: (res) => {
        this.setData({
          hotels: res.data || []
        });
      }
    });
  },
  
  // 预订门票
  bookTicket: function(e) {
    const ticketId = e.currentTarget.dataset.id;
    const ticket = this.data.tickets.find(item => item.id === ticketId);
    
    if (!ticket) {
      wx.showToast({
        title: '门票信息不存在',
        icon: 'none'
      });
      return;
    }
    
    // 检查用户是否登录
    const app = getApp();
    if (!app.checkLogin()) {
      wx.showModal({
        title: '提示',
        content: '预订门票需要先登录，是否前往登录？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    // 跳转到订单确认页面
    wx.navigateTo({
      url: `/pages/order/confirm/confirm?ticketId=${ticketId}&scenicId=${this.data.id}`
    });
  },
  
  // 选择日期
  selectDate: function(callback) {
    // 获取当前日期
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    
    // 默认选择明天
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const defaultDate = tomorrow.getFullYear() + '-' + 
                      (tomorrow.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                      tomorrow.getDate().toString().padStart(2, '0');
    
    // 日期选择对话框
    wx.showModal({
      title: '请选择使用日期',
      content: '请输入日期（格式：YYYY-MM-DD）',
      editable: true,
      placeholderText: defaultDate,
      success: (res) => {
        if (res.confirm) {
          // 简单验证日期格式
          const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
          let useDate = res.content || defaultDate;
          
          if (!dateRegex.test(useDate)) {
            wx.showToast({
              title: '日期格式不正确',
              icon: 'none'
            });
            return;
          }
          
          callback(useDate);
        }
      }
    });
  },
  
  // 创建订单
  createOrder: function(ticket, quantity, useDate, userId) {
    // 显示加载
    wx.showLoading({
      title: '正在创建订单...',
    });
    
    // 计算总金额
    const totalAmount = (ticket.price * quantity).toFixed(2);
    
    // 准备订单数据
    const orderData = {
      user: { id: userId },
      productId: ticket.id,
      type: 1,  // 1-门票订单
      quantity: quantity,
      totalAmount: totalAmount,  // 删除unitPrice字段，只保留totalAmount
      bookDate: new Date().toISOString().split('T')[0],
      useDate: useDate,
      status: 1  // 1-待支付
    };
    
    console.log('创建订单数据:', orderData);
    
    // 调用创建订单API
    wx.mRequest({
      url: '/api/order/create',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'  // 确保Content-Type设置正确
      },
      data: orderData,
      success: (res) => {
        wx.hideLoading();
        console.log('创建订单响应:', res);
        
        if (res.code === 0) {
          wx.showToast({
            title: '预订成功',
            icon: 'success',
            duration: 2000
          });
          
          // 跳转到订单详情页
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/order/order?tab=1'  // 1-待支付
            });
          }, 2000);
        } else {
          wx.showToast({
            title: res.msg || '预订失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('创建订单失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      }
    });
  },
  
  // 前往酒店详情
  goToHotel: function(e) {
    const hotelId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/hotel/detail/detail?id=' + hotelId
    });
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.loadData();
    wx.stopPullDownRefresh();
  },
  
  // 分享
  onShareAppMessage: function() {
    const scenicArea = this.data.scenicArea;
    return {
      title: scenicArea ? scenicArea.name : '景区详情',
      path: '/pages/scenic/detail/detail?id=' + this.data.id
    };
  }
}) 